import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getServices, createService, updateService, deleteService } from '@/api/service'
import { Message } from '@arco-design/web-vue'

export const useServiceStore = defineStore('service', () => {
  // 状态
  const services = ref([])
  const loading = ref(false)
  const pagination = ref({
    current: 1,
    size: 10,
    total: 0
  })
  const filters = ref({
    name: '',
    type_id: null
  })

  // 获取服务列表
  const fetchServices = async (params = {}) => {
    loading.value = true
    try {
      const data = await getServices({
        page: pagination.value.current,
        size: pagination.value.size,
        ...filters.value,
        ...params
      })
      
      console.log('=== 获取到服务数据 ===')
      console.log('原始数据:', data)
      console.log('data.list:', data?.list)
      console.log('data.total:', data?.total)
      
      // axios 响应拦截器已经返回了 data.data，所以这里直接使用
      services.value = data?.list || []
      pagination.value.total = data?.total || 0
      pagination.value.current = data?.page || 1
      
      console.log('解析后 services:', services.value)
      console.log('services 长度:', services.value.length)
      console.log('pagination:', pagination.value)
    } catch (error) {
      console.error('获取服务列表失败:', error)
      Message.error('获取服务列表失败')
      services.value = []
    } finally {
      loading.value = false
    }
  }

  // 创建服务
  const createServiceData = async (serviceData) => {
    try {
      await createService(serviceData)
      Message.success('服务创建成功')
      await fetchServices()
      return true
    } catch (error) {
      console.error('创建服务失败:', error)
      Message.error('创建服务失败')
      return false
    }
  }

  // 更新服务
  const updateServiceData = async (id, serviceData) => {
    try {
      await updateService(id, serviceData)
      Message.success('服务更新成功')
      await fetchServices()
      return true
    } catch (error) {
      console.error('更新服务失败:', error)
      Message.error('更新服务失败')
      return false
    }
  }

  // 删除服务
  const deleteServiceData = async (id) => {
    try {
      await deleteService(id)
      Message.success('服务删除成功')
      await fetchServices()
      return true
    } catch (error) {
      console.error('删除服务失败:', error)
      Message.error('删除服务失败')
      return false
    }
  }

  // 设置筛选条件
  const setFilters = (newFilters) => {
    filters.value = { ...filters.value, ...newFilters }
    pagination.value.current = 1
  }

  // 设置分页
  const setPagination = (newPagination) => {
    pagination.value = { ...pagination.value, ...newPagination }
  }

  // 重置筛选条件
  const resetFilters = () => {
    filters.value = {
      name: '',
      type_id: null
    }
    pagination.value.current = 1
  }

  return {
    // 状态
    services,
    loading,
    pagination,
    filters,
    
    // 方法
    fetchServices,
    createServiceData,
    updateServiceData,
    deleteServiceData,
    setFilters,
    setPagination,
    resetFilters
  }
})

